//
//  ProductViewController.m
//  KiklinkApp
//
//  Created by LJC on 14-9-29.
//  Copyright (c) 2014年 Kiklink. All rights reserved.
//

#import "ProductViewController.h"

#import "ImagesManager.h"
#import "UIColor+hex.h"
#import "UIView+loadWithNib.h"

#import "ProductImageCell.h"
#import "ProductBaseInfoCell.h"
#import "ProductExpandCell.h"
#import "ProductDetailInfoCell.h"
#import "ProductLocationCell.h"
#import "ProductPushCell.h"

#import "CoachViewController.h"
#import "RemarkViewController.h"
#import "SoldViewController.h"

#import "ScheduledViewController.h"

@interface ProductViewController ()
{
    //data
    ImagesManager *imagesManager;
    
    //ui
    ProductImageCell *imageCell;
    ProductBaseInfoCell *baseInfoCell;
    ProductExpandCell *detailExpandCell;
    ProductDetailInfoCell *detailInfoCell;
    ProductExpandCell *locationExpandCell;
    ProductLocationCell *locationCell;
    ProductPushCell *coachCell;
    ProductPushCell *remarkCell;
    ProductPushCell *soldCell;
    
    BOOL isDetailExpand;
    BOOL isLocationExpand;
    BOOL isMapLoaded;
}
@end

@implementation ProductViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"商品详情";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:AppColor_BackGround];

    
    //BundleImages
    imagesManager = [ImagesManager sharedImagesManager];
    
    
    //leftNavItem
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setFrame:CGRectMake(0, 0, NavBarHeight/4, NavBarHeight/2)];
    [backButton setBackgroundImage:[imagesManager back] forState:UIControlStateNormal];
    [backButton setBackgroundImage:[imagesManager backTapped] forState:UIControlStateHighlighted];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftNavBarItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftNavBarItem;
    
    
    //rightNavItem
    UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [shareButton setFrame:CGRectMake(0, 0, NavBarHeight/2.3, NavBarHeight/2.4)];
    [shareButton setBackgroundImage:[imagesManager share] forState:UIControlStateNormal];
    [shareButton setBackgroundImage:[imagesManager shareTapped] forState:UIControlStateHighlighted];
    [shareButton addTarget:self action:@selector(shareAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightNavBarItem = [[UIBarButtonItem alloc] initWithCustomView:shareButton];
    self.navigationItem.rightBarButtonItem = rightNavBarItem;
    
    
    //toolBar
    self.collectLabel.textColor = [UIColor colorWithHexString:AppColor_Text];
    self.buyBtn.backgroundColor = [UIColor colorWithHexString:AppColor_slider];
    [self.buyBtn.layer setMasksToBounds:YES];
    [self.buyBtn.layer setCornerRadius:5];
    [self.collectBtn addTarget:self action:@selector(collect) forControlEvents:UIControlEventTouchUpInside];
    [self.buyBtn addTarget:self action:@selector(buy) forControlEvents:UIControlEventTouchUpInside];
    
    
    //productTable
    self.edgesForExtendedLayout = UIRectEdgeBottom;
    self.productTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.productTable.backgroundColor = [UIColor colorWithHexString:AppColor_BackGround];
    self.productTable.delegate = self;
    self.productTable.dataSource = self;
    self.productTable.showsVerticalScrollIndicator = NO;
    
    imageCell = [ProductImageCell loadWithNib:@"ProductImageCell" AndPostion:CGPointZero];
    
    baseInfoCell = [ProductBaseInfoCell loadWithNib:@"ProductBaseInfoCell" AndPostion:CGPointZero];
    
    isDetailExpand = NO;
    detailExpandCell = [ProductExpandCell loadWithNib:@"ProductExpandCell" AndPostion:CGPointZero];
    detailExpandCell.titleLabel.text = @"详细信息";
    [detailExpandCell.expandBtn addTarget:self action:@selector(detailInfoExpand) forControlEvents:UIControlEventTouchUpInside];
    
    detailInfoCell = [ProductDetailInfoCell loadWithNib:@"ProductDetailInfoCell" AndPostion:CGPointZero];
    [detailInfoCell.shrinkBtn addTarget:self action:@selector(detailInfoShrink) forControlEvents:UIControlEventTouchUpInside];
    
    isLocationExpand = NO;
    locationExpandCell = [ProductExpandCell loadWithNib:@"ProductExpandCell" AndPostion:CGPointZero];
    locationExpandCell.titleLabel.text = @"地理位置";
    [locationExpandCell.expandBtn addTarget:self action:@selector(locationExpand) forControlEvents:UIControlEventTouchUpInside];
    
    locationCell = [ProductLocationCell loadWithNib:@"ProductLocationCell" AndPostion:CGPointZero];
    [locationCell.shrinkBtn addTarget:self action:@selector(locationShrink) forControlEvents:UIControlEventTouchUpInside];
    [locationCell.phoneBtn addTarget:self action:@selector(phoneCall) forControlEvents:UIControlEventTouchUpInside];
    isMapLoaded = NO;

    
    coachCell = [ProductPushCell loadWithNib:@"ProductPushCell" AndPostion:CGPointZero];
    coachCell.titleLabel.text = @"教练信息";
    [coachCell.pushBtn addTarget:self action:@selector(coachPush) forControlEvents:UIControlEventTouchUpInside];
    
    remarkCell = [ProductPushCell loadWithNib:@"ProductPushCell" AndPostion:CGPointZero];
    remarkCell.titleLabel.text = @"服务评价";
    [remarkCell.pushBtn addTarget:self action:@selector(remarkPush) forControlEvents:UIControlEventTouchUpInside];
    
    soldCell = [ProductPushCell loadWithNib:@"ProductPushCell" AndPostion:CGPointZero];
    soldCell.titleLabel.text = @"成交记录";
    [soldCell.pushBtn addTarget:self action:@selector(soldPush) forControlEvents:UIControlEventTouchUpInside];
    
    //data
    [self getData];
}

#pragma mark - get data
- (void)getData
{
    if (self.product) {
        
        [self getShop];
        [self loadData];

    } else {
        
        [API productDetailWithId:[NSNumber numberWithInteger:self.productID] Callback:^(int stateCode, NSString *word, id content) {
            
            if (stateCode == SUCCESS) {
                
                Product *product = (Product *)content;
                self.product = product;
                [self getShop];
                [self loadData];
                
            } else {
                
                baseInfoCell.nameLabel.text = @"     ";
                detailInfoCell.nameLabel.text = @"    ";
                detailInfoCell.placeLabel.text = @"    ";
                
            }
            
        }];
        
    }
    
}
- (void)loadData
{
    [self.productTable reloadData];
    [self getIsCollected];
}
- (void)getShop
{
    [API shopDetailWithShopId:[NSNumber numberWithInteger:self.product.shopId] Callback:^(int stateCode, NSString *word, id content) {
        
        if (stateCode == SUCCESS) {
            
            Shop *shop = (Shop *)content;
            detailInfoCell.telLabel.text = shop.phoneno;
            detailInfoCell.emailLabel.text = shop.email;
            locationCell.telLabel.text = shop.phoneno;
            [self.productTable reloadData];

        } else {
        }
        
    }];
}

- (void)getIsCollected
{
    LoginStatus = [AccountManager isKiklinkLoggedin];
    if (LoginStatus == YES) {
        
        [API favouriteProductPageWithProductId:[NSNumber numberWithInteger:self.productID] Callback:^(int stateCode, NSString *word, id content) {
            
            if (stateCode == SUCCESS) {
                
                FavouriteItemPage* favouriteItemPage = (FavouriteItemPage *)content;
                if (favouriteItemPage.totalCount != 0) {
                    
                    self.isCollected = YES;
                    [self changeCollectionItem];

                } else {
                    
                    self.isCollected = NO;
                    [self changeCollectionItem];

                }
                
            } else {
                
                self.isCollected = NO;
                [self changeCollectionItem];

            }
            
        }];
        
    } else {
        
        self.isCollected = NO;
        [self changeCollectionItem];
        
    }
    
}
- (void)changeCollectionItem
{
    if (self.isCollected) {
        self.collectIcon.image = [imagesManager collected];
        self.collectLabel.text = @"已收藏";
    } else {
        self.collectIcon.image = [imagesManager unCollected];
        self.collectLabel.text = @"收藏";
    }
}
- (void)doCollect
{
    self.collectBtn.userInteractionEnabled = NO;
    [API addFavouriteProductWithProductId:[NSNumber numberWithInteger:self.productID] Callback:^(int stateCode, NSString *word, id content) {
        
        self.collectBtn.userInteractionEnabled = YES;

        if (stateCode == SUCCESS) {
            
            self.collectIcon.image = [imagesManager collected];
            self.collectLabel.text = @"已收藏";
            self.isCollected = YES;

        } else {
            
            self.collectIcon.image = [imagesManager unCollected];
            self.collectLabel.text = @"收藏";
            self.isCollected = NO;

        }
        
    }];
}
- (void)undoCollect
{
    self.collectBtn.userInteractionEnabled = NO;

    [API favouriteProductPageWithProductId:[NSNumber numberWithInteger:self.productID] Callback:^(int stateCode, NSString *word, id content) {
        
        if (stateCode == SUCCESS) {
            
            FavouriteItemPage* favouriteItemPage = (FavouriteItemPage *)content;
            NSMutableArray *result = [[NSMutableArray alloc] initWithArray:favouriteItemPage.result];
            FavouriteItem *favouriteItem = (FavouriteItem *)[result objectAtIndex:0];
            [API removeFavouriteItemWithFavouriteId:favouriteItem.id Callback:^(int stateCode, NSString *word, id content) {
                
                self.collectBtn.userInteractionEnabled = YES;

                if (stateCode == SUCCESS) {
                    self.collectIcon.image = [imagesManager unCollected];
                    self.collectLabel.text = @"收藏";
                    self.isCollected = NO;
                } else {
                    self.collectIcon.image = [imagesManager collected];
                    self.collectLabel.text = @"已收藏";
                    self.isCollected = YES;
                }
                
            }];
            
        } else {
            self.collectBtn.userInteractionEnabled = YES;

            self.collectIcon.image = [imagesManager collected];
            self.collectLabel.text = @"已收藏";
            self.isCollected = YES;
        }
        
    }];
}
#pragma mark - get data End

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    
    if (self.product) {
        [self getIsCollected];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [locationCell.mapView onViewWillDisappear];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - back
- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - back End

#pragma mark - shareAction
- (void)shareAction
{
    if (self.product) {
        [AccountManager openSNSShareUIWithSharedText:[NSString stringWithFormat:@"%@",self.product.name] shareImage:nil];
    }
}
#pragma mark - shareAction End

#pragma mark - detailInfoShrink
- (void)detailInfoShrink
{
    isDetailExpand = NO;
    [self.productTable reloadData];
    
    CATransition *animation = [CATransition animation];
    animation.duration = 0.1;
    animation.type = @"fade";
    animation.subtype = @"fromTop";
    [self.productTable.layer addAnimation:animation forKey:nil];
}
#pragma mark - detailInfoShrink End

#pragma mark - detailInfoExpand
- (void)detailInfoExpand
{
    isDetailExpand = YES;
    isLocationExpand = NO;
    [self.productTable reloadData];
}
#pragma mark - detailInfoExpand End

#pragma mark - locationShrink
- (void)locationShrink
{
    isLocationExpand = NO;
    [self.productTable reloadData];
    
    CATransition *animation = [CATransition animation];
    animation.duration = 0.1;
    animation.type = @"fade";
    animation.subtype = @"fromTop";
    [self.productTable.layer addAnimation:animation forKey:nil];
}
#pragma mark - locationShrink End

#pragma mark - locationExpand
- (void)locationExpand
{
    isLocationExpand = YES;
    isDetailExpand = NO;
    [self.productTable reloadData];
    
    if (!isMapLoaded) {
        if (self.product) {
            [locationCell.mapView setPinWithWord:@"" longitude:self.product.mapx latitude:self.product.mapy];
            isMapLoaded = YES;
        }
    }
}
#pragma mark - locationExpand End

#pragma mark - phoneCall
- (void)phoneCall
{
    UIActionSheet *phoneSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:locationCell.telLabel.text, nil];
    [phoneSheet showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://00000000000"]]];
    }
}
#pragma mark - phoneCall End

#pragma mark - coachPush
- (void)coachPush
{
    CoachViewController *coachVC = [[CoachViewController alloc] init];
    coachVC.productID = self.productID;
    [self.navigationController pushViewController:coachVC animated:YES];
}
#pragma mark - coachPush End

#pragma mark - remarkPush
- (void)remarkPush
{
    RemarkViewController *remarkVC = [[RemarkViewController alloc] init];
    remarkVC.productID = self.productID;
    remarkVC.product = self.product;
    [self.navigationController pushViewController:remarkVC animated:YES];
}
#pragma mark - remarkPush End

#pragma mark - soldPush
- (void)soldPush
{
    SoldViewController *soldVC = [[SoldViewController alloc] init];
    soldVC.productID = self.productID;
    soldVC.product = self.product;
    [self.navigationController pushViewController:soldVC animated:YES];
}
#pragma mark - soldPush End

#pragma mark - collect
- (void)collect
{
    if (self.isCollected) {
        [self undoCollect];
    } else {
        [self doCollect];
    }
}
#pragma mark - collect End

#pragma mark - buy
- (void)buy
{
    LoginStatus = [AccountManager isKiklinkLoggedin];
    if (LoginStatus == YES) {
        
        ScheduledViewController *scheduledVC = [[ScheduledViewController alloc] init];
        scheduledVC.productID = self.productID;
        scheduledVC.productName = self.product.name;
        scheduledVC.price = self.product.price;
        [self.navigationController pushViewController:scheduledVC animated:YES];
        
    } else {
        [AccountManager openLoginUI];
    }
}
#pragma mark - buy End

#pragma tableView dataSource&delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 7;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        if (self.product) {
            [imageCell loadDataWithProduct:self.product];
        }
        return imageCell;
    } else if (indexPath.row == 1) {
        if (self.product) {
            [baseInfoCell loadDataWithProduct:self.product];
        }
        return baseInfoCell;
    } else if (indexPath.row == 2) {
        if (isDetailExpand) {
            if (self.product) {
                [detailInfoCell loadDataWithProduct:self.product];
            }
            return detailInfoCell;
        } else {
            return detailExpandCell;
        }
    } else if (indexPath.row == 3) {
        if (isLocationExpand) {
            if (self.product) {
                [locationCell loadDataWithProduct:self.product];
            }
            return locationCell;
        } else {
            return locationExpandCell;
        }
    } else if (indexPath.row == 4) {
        return coachCell;
    } else if (indexPath.row == 5) {
        return remarkCell;
    } else {
        return soldCell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 179;
    } else if (indexPath.row == 1) {
        return 132;
    } else if (indexPath.row == 2) {
        if (isDetailExpand) {
            return 332;
        } else {
            return 52;
        }
    } else if (indexPath.row == 3) {
        if (isLocationExpand) {
            return 343;
        } else {
            return 52;
        }
    } else {
        return 52;
    }
}
#pragma tableView dataSource&delegate End

@end
